//
//  MemoryViewController.m
//  OurJourney
//
//  Created by 李沛池 on 2017/4/1.
//  Copyright © 2017年 Godlike. All rights reserved.
//

#import "MemoryViewController.h"
#import "MemoryCollectionViewCell.h"
#import "WSLayout.h"
#import "LPCTools.h"
#import "LPCDefine.h"
#import "LPCSettingManager.h"
#import <MBProgressHUD+JDragon.h>
#import "LPCInfoManager.h"

#define TAG_ActionSheet_TakePhoto   520
#define TAG_ActionSheet_DeletePhoto 521

@interface MemoryViewController ()<
UIActionSheetDelegate,
UICollectionViewDelegate,
UICollectionViewDataSource,
UINavigationControllerDelegate,
UIImagePickerControllerDelegate>

@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) WSLayout *wslayout;

@end

@implementation MemoryViewController
{
    UILongPressGestureRecognizer *_longPressGR;
    NSIndexPath *_currentSelectedIP; //当前选中的IndexPath
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
}

- (void)initData
{
    _arrayData = [LPCInfoManager sharedLPCInfoManager].arrayLovePictures;
}

- (void)initUI
{
    [self initCollectionView];
}

- (void)initCollectionView
{
    self.wslayout = [[WSLayout alloc] init];
    self.wslayout.lineNumber = 2; //列数
    self.wslayout.rowSpacing = 5; //行间距
    self.wslayout.lineSpacing = 5; //列间距
    self.wslayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    // 透明时用这个属性(保证collectionView 不会被遮挡, 也不会向下移)
    //self.edgesForExtendedLayout = UIRectEdgeNone;
    // 不透明时用这个属性
    //self.extendedLayoutIncludesOpaqueBars = YES;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(15, 15 + 30 + 5, self.view.frame.size.width - 30, self.view.frame.size.height - 30 - 30 - 5 - 49) collectionViewLayout:self.wslayout];
    
    [self.collectionView registerClass:[MemoryCollectionViewCell class] forCellWithReuseIdentifier:@"collectionCell"];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.collectionView];
    
    //长按删除
    _longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(deletePicture:)];
    [self.collectionView addGestureRecognizer:_longPressGR];
    
    //返回每个cell的高   对应indexPath
    [self.wslayout computeIndexCellHeightWithWidthBlock:^CGFloat(NSIndexPath *indexPath, CGFloat width) {
        
        NSString *imagePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"LovePictures.bundle/%@", _arrayData[indexPath.row]]];
        if (![[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
            imagePath = [PATH_LovePictures stringByAppendingPathComponent:_arrayData[indexPath.row]];
        }
        CGSize size = [UIImage imageWithContentsOfFile:imagePath].size;
        
        CGFloat oldWidth = size.width;
        CGFloat oldHeight = size.height;
        
        CGFloat newWidth = width;
        CGFloat newHeigth = oldHeight*newWidth / oldWidth;
        return newHeigth;
    }];
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _arrayData.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MemoryCollectionViewCell *cell = (MemoryCollectionViewCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];
    
    [cell setResourceName:_arrayData[indexPath.row]];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MemoryCollectionViewCell *cell = (MemoryCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    //放大显示图片
    [LPCTools showImage:cell.iView];
}

//返回主页
- (IBAction)backHome:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

//添加照片
- (IBAction)addPicture:(UIButton *)sender
{
    [self showTakePhotoActionSheet];
}

- (void)showTakePhotoActionSheet
{
    NSString *cancelStr = @"取消";
    NSArray *Titles = @[@"拍照",@"从相册中选取"];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:cancelStr
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:Titles[0],Titles[1],nil];
    actionSheet.tag = TAG_ActionSheet_TakePhoto;
    [actionSheet showInView:self.view];
}

//删除图片
- (void)deletePicture:(UILongPressGestureRecognizer *)longPressGR
{
    _currentSelectedIP = [_collectionView indexPathForItemAtPoint:[_longPressGR locationInView:_collectionView]];
    if (longPressGR.state == UIGestureRecognizerStateBegan) {
        [self showDeletePhotoActionSheet];
    }
}

- (void)showDeletePhotoActionSheet
{
    NSArray *Titles = @[@"删除",@"保存至相册"];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:Titles[0],Titles[1],nil];
    actionSheet.tag = TAG_ActionSheet_DeletePhoto;
    [actionSheet showInView:self.view];
}

//把图片写入沙盒
- (void)writeImageFile:(UIImage *)pickImage
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //查询文件夹下有多少文件
    if (![fileManager fileExistsAtPath:PATH_LovePictures]) {
        [fileManager createDirectoryAtPath:PATH_LovePictures withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSArray *arrayImages = [fileManager contentsOfDirectoryAtPath:PATH_LovePictures error:nil];
    //图片名称
    NSString *imageName = [NSString stringWithFormat:@"lovePictures_%d.png",(int)arrayImages.count + 1];
    //设置一个图片的存储路径
    NSString *imagePath = [PATH_LovePictures stringByAppendingPathComponent:imageName];
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    [UIImagePNGRepresentation(pickImage) writeToFile:imagePath atomically:YES];
    
    [_arrayData insertObject:imageName atIndex:0];
}

//基于新生成的图片刷新collectionView
- (void)reloadCollectionView
{
    [_collectionView removeFromSuperview];
    
    [self initUI];
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == TAG_ActionSheet_TakePhoto) {
        switch (buttonIndex) {
            case 0://照相机
            {
                UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
                imagePicker.delegate = self;
                imagePicker.allowsEditing = YES;
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imagePicker animated:YES completion:nil];
                
            }
                break;
            case 1://相册
            {
                UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
                imagePicker.delegate = self;
                imagePicker.allowsEditing = YES;
                imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:imagePicker animated:YES completion:nil];
            }
                break;
            default:
                break;
        }
    }else {
        switch (buttonIndex) {
            case 0://删除图片
            {
                if ([[LPCSettingManager sharedLPCSettingManager].userId isEqualToString:@"Godlike"]) { //试用版本不可执行删除操作
                    [MBProgressHUD showTipMessageInWindow:@"试用版本不可执行删除操作"];
                }else {
                    NSString *imageName = _arrayData[_currentSelectedIP.item];
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    NSString *imagePath = [PATH_LovePictures stringByAppendingPathComponent:imageName];
                    if ([fileManager fileExistsAtPath:imagePath]) {
                        [fileManager removeItemAtPath:imagePath error:nil];
                    }else {
                        NSMutableArray *arrayLovePicturesHidePlist = [NSMutableArray arrayWithContentsOfFile:PATH_LovePicturesHidePlist];
                        if (!arrayLovePicturesHidePlist) {
                            arrayLovePicturesHidePlist = [[NSMutableArray alloc] init];
                        }
                        [arrayLovePicturesHidePlist addObject:imageName];
                        [arrayLovePicturesHidePlist writeToFile:PATH_LovePicturesHidePlist atomically:YES];
                    }
                    [_arrayData removeObject:imageName];
                    [self reloadCollectionView];
                }
            }
                break;
            case 1://保存至相册
            {
                MemoryCollectionViewCell *cell = (MemoryCollectionViewCell *)[_collectionView cellForItemAtIndexPath:_currentSelectedIP];
                [LPCTools saveImageToPhotos:cell.iView.image];
            }
                break;
            default:
                break;
        }
    }
    
    return;
}


#pragma UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *pickImage = info[UIImagePickerControllerEditedImage];
    
    [self writeImageFile:pickImage];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
        [self reloadCollectionView];
        
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}



















@end
